package com.nexgo.data.entity.mapper;

import com.nexgo.common.ByteUtils;
import com.nexgo.data.entity.RecvData;
import com.nexgo.data.entity.SendData;
import com.nexgo.data.json.JsonRecData;
import com.nexgo.data.json.JsonTools;
import com.nexgo.data.json.bean.SendBodyData;
import com.nexgo.iso8583.ConfigParser;
import com.nexgo.iso8583.LenType;
import com.nexgo.iso8583.Message;
import com.nexgo.iso8583.MessageFactory;
import com.nexgo.iso8583.exception.ParseException;
import com.nexgo.iso8583.exception.WriteException;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.entity.MessageData;
import com.nexgo.payment.pack.OnCalcMacListener;
import com.nexgo.payment.pack.OnCalcSignListener;
import com.nexgo.payment.util.ByteUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * Created by xiaox on 2017/6/2.
 */

public class EntityDataMapper {
    private Logger mLog = LoggerFactory.getLogger(EntityDataMapper.class.getSimpleName());
    private static final int HEADER_LENGTH = 5;

    private static MessageFactory mft = null;

    static {
        InputStream is = EntityDataMapper.class.getResourceAsStream("/assets/iso8583.xml");
        try {
            mft = ConfigParser.createFromStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 接收数据包转换成对象
     *
     * @param recvData 后台返回Json包数据
     * @return 接收数据对象
     * @throws ParseException 解包失败
     */
    public Object transform(byte[] recvData) throws ParseException {
        //test
        /*String str = "{\"RSP_HEAD\":{\"TRACE_NO\":\"2040000420180329JP3326253658\",\"TRAN_SUCCESS\":\"1\"},\"RSP_BODY\":\"\"}";
//        String str = "{\"RSP_HEAD\":{\"TRACE_NO\":\"2040000420180329JP3326253658\",\"TRAN_SUCCESS\":\"1\"},\"RSP_BODY\":{\"responseMessage\":\"交易成功\",\"responseType\":\"N\",\"DECRYPT\":\"DA3BA6759E7B3B4B0F61AF0D6628716F4CB0F7B9D264886E0CE440E4EFC60B4E4F565253D4BAFA44C957DF5FC676D86375FB9A6ACF691A88E87FB463B1B2C2EABAD4899808423E5DFBBD17F45B104566C865A5818E276AB70D5FE10D2BEC325DE8A2B50BE0A746CEF52AFCF33ED604B834341590AF28758B3362BB1BD1A6B860B983976134A6211013E997BA5C92898B2C36AB0C0D4B916F14CEE43B305F50781CC5C8927FD63242A929383CAB9144D55742E64046A44925B8CACF9C48A7727E9BE023986DD1D5415F182EC225530E65F55C8E22EF4B20725798D8AE2864AEB4B21883E26DEDE16CD566246A96FD7C6F41A152CD1D3D898E52AD26219E2344D65F1FBB7AF88610E60721D6D05F30E3760B8DCCA09E5C6E4717ED97D66889C6A34DE78715244CA9488FB956F3B2F4BFEFE450DE837DAA86A2D7E08943051EC82EF898DCE59FFB6204E349681C50BA2D7967E476F34E03242E063C0B07A05470E87E97EFA29F6EC10758490E24011DC0C13E6133AAA2B9543F8A02E174E0822858AA68EDFD44AE99ED61ABA6DE1F757CF92D3A7B0467FC77BE2C392655944B59AED9C07F234086923E32D41CD34536C4F0\",\"responseCode\":\"CIPP0004PY0000\"}}";
        recvData = str.getBytes();*/
        MessageData msg = null;
        mLog.debug("response msg\n{}", ByteUtils.byteArray2HexString(recvData));

        JsonRecData jsonRecData = null;
        jsonRecData = JsonTools.fromJson(new String(recvData),JsonRecData.class);
        if (jsonRecData == null){
            mLog.debug("解包失败");
        }
        /*//test
        if(jsonRecData.getREQ_BODY() == null){
            mLog.debug("body is null");
        }else if(jsonRecData.getREQ_BODY().equals("")){
            mLog.debug("body is ");
        }*/

        msg = new MessageData();
        msg.setJsonRecData(jsonRecData);


        return msg;
    }

    /**
     * 发送数据对象转换为8583包数据格式
     *
     * @param sendData 发送数据对象
     * @return 8583包数据
     * @throws WriteException 组包失败
     */
    public byte[] transform(SendData sendData) throws WriteException {
        byte[] msg = null;
        if (mft != null) {
            Message message = mft.newMessage();
            byte[] data = message.writeData(sendData);
            OnCalcMacListener listener = sendData.getListener();
            if (message.hasField(64) && listener != null) {
                byte[] mac = listener.getMac(Arrays.copyOfRange(data, 0, data.length - 8));
                message.setValue(64, ByteUtils.byteArray2HexString(mac));
            }
            msg = message.write(2, LenType.HEX);
            mLog.debug("request msg\n{}", ByteUtils.byteArray2HexString(msg));
            mLog.debug("request msg\n{}", message.toString());
        }


        return msg;
    }

    /**
     * 发送数据对象转换为json
     *
     * @param sendData 发送数据对象
     * @return json包数据
     * @throws WriteException 组包失败
     */
    public byte[] transform(Object sendData) throws WriteException {
        byte[] msg = null;

        MessageData data = (MessageData) sendData;

        SendBodyData sendBodyData = data.getJsonSendData().getREQ_BODY();

        String str = "REQ_MESSAGE=";

        //test
        //加密body
//        String str1 = "AC023F7C1079DE044A87AB787D0E8E97D7B9E91E9D188C22233313A67963E100E62AC77F533E16D840F80664737238F9C3FF4629A34DE5A3465617800430117E99757BFE0F7010B05BBAAC41A792AA69F6F239E50397F0BD8AD5CA4437E3A8A30CF8870242573EBA169C9A78DEAE666F5960607551580B8D24A53AF60EEA7D82D2943F90E750FF642F0C293A8DA486A22463A399346D05FED6EEBE9587AA9897BB81845350B57780B407B9B19BBE4580BD76D0E0597A735465359E200A1A5F80F9B6F2232A1B022138D49AB2E6752B73";
        /*String str1 = "18D70C07AB14D11C09F75C28D3E1F6BF90FC1F317D22B801954A07C82F46C2931A2882E96823509CF8D4CF0DD03E86A18C7756F4B13CFFA1BAA277B2667EB33A9EECAB49F5BD7337257D2431339DBE29AD95243559CACB9DDA7FF8A12502FD0F918968736D86EA6B1BC70B9218DD4724486A26A34F4001FA7E34FFA761CC331566135D0675DD4B93375BE0D16EE8A10E9A78A895BEB524EDE7D6870B4E29F9C29A78A895BEB524EDE7D6870B4E29F9C29A78A895BEB524EDE7D6870B4E29F9C20FE3E23CAB80786C46FEB34BFA07D324D0414F5150DC7B328D33A7C1F41AA7B8065EF8FCC48C9589DE4FA55412FD3B0B95C9BE5531369CDAF423D139090B70BA968AB9B3696892CA3D2D0646B311E5EC77230FB413683DACA54F082DC0BC20A8332A0875274D3BB6427806A61B7B660C0F50895F448EB270D3B2DCA5AAD95723201C0E78D80B6C39F374F47F00FB621B0221390ACB017BAC61E0363CEB90A8EF";
        try {
            String str2 = UnionApi.getInstance().DecryptData(2,"CIPP050001","301140858120001","20180327101918",str1);
            mLog.debug("str2 = {}",str2);
        } catch (Exception e) {
            mLog.debug("解密失败");
            e.printStackTrace();
        }*/

        String enData = sendBodyData.getDECRYPT();
        mLog.debug("加密前数据={}",sendBodyData.getDECRYPT());
        //签名
        if(data.getJsonSendData().getREQ_HEAD().getSign() != null) {
            OnCalcSignListener listener = data.getSendData().getSignListener();
            data.getJsonSendData().getREQ_HEAD().setSign(listener.getSign(data.getJsonSendData()).toUpperCase());
        }else{
            data.getJsonSendData().getREQ_HEAD().setSign("");
        }

        try {
            //xhj add
//             sendBodyData.setDECRYPT(UnionApi.getInstance().EncryptPlianData(2,data.getJsonSendData().getREQ_HEAD().getTranscode(),
//                    data.getJsonSendData().getREQ_HEAD().getMcht_id(),data.getJsonSendData().getREQ_HEAD().getTerm_trans_time(),
//                    enData.substring(1,enData.length()-1)));
            String s = ByteUtil.CalcByWKey(enData.substring(1, enData.length() - 1), false);
            sendBodyData.setDECRYPT(s);
            /*String s1 = ByteUtil.CalcByWKey(s, true);
            mLog.debug("解密后的数据：{}",s1);*/
        } catch (Exception e) {
            mLog.debug("加密失败");
            e.printStackTrace();
        }
        //xhj add
        mLog.debug("新增TERMINAL_ID");
        sendBodyData.setTerm_id(Repository.getInstance().getParamValue(PreferencesConstants.TERMINAL_ID));
        data.getJsonSendData().setREQ_BODY(sendBodyData);
        msg = (str + JsonTools.toJson(data.getJsonSendData())).getBytes();

        mLog.debug("request msg\n{}", str+ JsonTools.toJson(data.getJsonSendData()));


        return msg;
    }

    //lr add解8583包
    public RecvData rTransform(byte[] recvData) throws ParseException {
        RecvData msg = null;
        if (mft != null) {
            mLog.debug("response msg\n{}", ByteUtils.byteArray2HexString(recvData));
            msg = new RecvData();
            //接收的8583报文前4个字节是长度
            Message message = mft.parseMessage(msg, Arrays.copyOfRange(recvData, 2, recvData.length), 0);
            msg.setMessage(message);
            mLog.debug("response msg\n{}", message.toString());
        }
        return msg;
    }


}
